<!DOCTYPE html>
<body>
  <div
    id="box"
    style="width: 100px; height: 100px; background-color: red"
  ></div>
  <p>键盘：<a href="javascript:fireKeyEvent('keydown')">keydown</a></p>
  <p>鼠标: <a href="javascript:fireMouseEvent('mousedown')">mousedown</a></p>
  <hr />
  <div id="log" style="width: 100%">Event Log:</div>
</body>
<script>
  document.addEventListener("keyup", function (e) {
    console.log("keyup", e);
    log("keyup:" + e.key);
  });
  document.addEventListener("keydown", function (e) {
    console.log("keydown", e);
    log("keydown:" + e.key);
  });
  document.addEventListener("keypress", function (e) {
    console.log("keyup", e);
    log("keypress:" + e.key);
  });

  document.onmousedown = function (e) {
    console.log("mousedown", e);
    log("mousedown:[" + e.screenX + "," + e.screenY + "]");
  };

  document.onmouseup = function (e) {
    console.log("mouseup", e);
    log("mouseup:[" + e.screenX + "," + e.screenY + "]");
  };

  document.onmousemove = function (e) {
    console.log("mousmove", e);
    log("mousmove:[" + e.screenX + "," + e.screenY + "]");
  };

  function log(text) {
    var div = document.getElementById("log");
    div.insertAdjacentHTML("afterend", "<p>" + text + "</p>");
  }

  //type:keydown, keyup, keypress
  function fireKeyEvent(type) {
    var e = new KeyboardEvent(type, {
      key: "a",
      ctrlKey: false,
      shiftKey: false,
      altKey: false,
      metaKey: false,
      bubbles: true,
      cancelable: true,
    });
    document.dispatchEvent(e);
  }

  //
  function fireMouseEvent(type) {
    var e = new MouseEvent(type);
    e.initMouseEvent(
      type,
      true, //bubbles
      true, //cancelable
      window, //view
      0, //detail
      1724, //screenX
      219, //screenY
      0, //clientX
      0, //clientY
      false, //ctrlKey
      false, //altKey
      false, //shiftKey
      false, //metaKey
      0, //button
      null //relateTarget
    );
    document.dispatchEvent(e);
  }

  var box = document.getElementById("box");
  box.addEventListener("click", function (e) {
    log("box click:[" + e.screenX + "," + e.screenY + "]");
  });
</script>
